<template>
  <div>
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="mini">

      <el-form-item label="项目区域" prop="projectRegion">
        <el-select v-model="queryParams.projectRegion" clearable placeholder="请选择" @keyup.enter.native="handleQuery">
          <el-option v-for="dict in dict.type.cld_project_region" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" clearable placeholder="请输入项目名称"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="负责人" prop="headPerson">
        <el-input v-model="queryParams.headPerson" clearable placeholder="请输入负责人"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleContractQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetContractQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="projectList" border>
      <el-table-column align="center" label="项目区域" prop="projectRegion" width="120px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_region" :value="scope.row.projectRegion"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目名称" prop="projectName" width="200px;"/>
      <el-table-column align="center" label="项目业态" prop="projectBusiness" width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_business" :value="scope.row.projectBusiness"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目类型" prop="projectType" width="100px;">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_type" :value="scope.row.projectType"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="负责人" prop="headPerson" width="100px;"/>
      <el-table-column align="center" label="联系电话" prop="headPhone" width="120px;"/>
      <el-table-column align="center" label="合同状态" prop="contractStatus" width="80px;">
        <template slot-scope="scope">
          <dict-tag :options="cldContractStatusOptions" :value="parseInt(scope.row.contractStatus)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="签订日期" prop="signDate" width="100px;"/>
      <el-table-column align="center" label="合同开始日期" prop="startDate" width="100px;"/>
      <el-table-column align="center" label="合同结束日期" prop="endDate" width="100px;"/>
      <el-table-column align="center" label="合同到期天数" prop="contractEndDay" width="100px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.contractEndDay > 10" type="success">{{scope.row.contractEndDay}}</el-tag>
          <el-tag v-if="scope.row.contractEndDay <= 10" type="danger">{{scope.row.contractEndDay}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="结算日" prop="settlementDay" width="80px;">
      </el-table-column>
      <el-table-column align="center" label="合同人数" prop="contractNumber" width="80px;">
      </el-table-column>
      <el-table-column align="center" label="在岗人数" prop="staffNumber" width="80px;">
      </el-table-column>
      <el-table-column label="项目地址" prop="address"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250px;">
        <template slot-scope="scope">
          <el-button v-hasPermi="['cld:project:config']" size="mini" type="text"
                     @click="handleContractSet(scope.row)">項目配置
          </el-button>
          <el-button v-hasPermi="['cld:project:estimate']" size="mini" type="text"
                     @click="handleProfitEstimation(scope.row)">计划设置
          </el-button>
          <el-button v-hasPermi="['cld:project:termination']" size="mini" type="text"
                     @click="handleTermination(scope.row)">终止项目
          </el-button>
          <el-dropdown v-hasPermi="['cld:project:addGroup', 'cld:project:addWorkPlan', 'cld:project:checkIn', 'cld:project:addProjectAssets', 'cld:project:viewPost'
            , 'cld:project:addCustomerAccount', 'cld:project:renewal', 'cld:project:remove'
          ]" size="mini" @command="(command) => handleCommand(command, scope.row)">
            <el-button icon="el-icon-d-arrow-right" size="mini" type="text">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-hasPermi="['cld:project:addGroup']" command="handleAddGroup"
                                icon="el-icon-files">设置项目小组
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:project:addWorkPlan']" command="handleAddWorkPlan"
                                icon="el-icon-edit-outline">设置工作计划
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:project:checkIn']" command="handleCheckIn"
                                icon="el-icon-map-location">设置打卡地址
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:project:addProjectAssets']" command="handleAddProjectAssets"
                                icon="el-icon-truck">设置项目资产
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:project:viewPost']" command="handleViewPost"
                                icon="el-icon-postcard">查看项目岗位
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:project:addCustomerAccount']" command="handleAddCustomerAccount"
                                icon="el-icon-user">客户账号
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cld:project:renewal']" command="handleRenewal"
                                icon="el-icon-tickets">续签项目
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
                @pagination="getContractList"/>

    <!-- 添加或修改项目对话框 -->
    <el-dialog v-if="openSet" :close-on-click-modal="false" :visible.sync="openSet" append-to-body title="项目配置" width="50%">
      <el-tabs v-model="activeSetName" type="border-card" @tab-click="handleTabClick">
        <el-tab-pane label="项目信息" name="project">
          <add-project v-if="activeSetName == 'project'" ref="addProject" :projectId="projectObj.projectId"
                       @success="handleSubmiSuccess"/>
        </el-tab-pane>
        <el-tab-pane label="合同信息" name="contract">
          <add-contract v-if="activeSetName == 'contract'" ref="addContract" :projectId="projectObj.projectId"
                        @success="handleSubmiSuccess"></add-contract>
        </el-tab-pane>
        <el-tab-pane label="项目配置" name="groupConfig">
          <add-configuration v-if="activeSetName == 'groupConfig'" ref="addConfiguration" :projectObj="projectObj"
                             @success="handleSubmiSuccess"></add-configuration>
        </el-tab-pane>
        <el-tab-pane label="物资配置阈值" name="material">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button icon="el-icon-plus" plain size="mini" type="primary" @click="handleAddCommodity">新增商品</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange" border>
            <el-table-column align="center" label="商品编号" prop="commodityNo"/>
            <el-table-column align="center" label="商品名称" prop="commodityName1"/>
            <el-table-column align="center" label="品牌" prop="commodityBrand"/>
            <el-table-column align="center" label="规格" prop="commoditySpec"/>
            <el-table-column align="center" label="单位" prop="unitName1"/>
            <el-table-column align="center" label="配送阈值" prop="commodityNum" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.commodityNum" onkeyup="this.value = this.value.replace(/[^A-z0-9]/, '')"
                          type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template slot-scope="scope">
                <el-button icon="el-icon-delete" size="mini" type="text"
                           @click="handleDeleteCommodity(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSetForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body
               title="选择商品"
               width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" isSymbol="1"
                    @SelectionChange="handleSelectionChange">
      </ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 项目终止 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isTerminationOpen" append-to-body
               title="项目终止"
               width="500px">
      <el-form ref="formTermination" :model="formTermination" label-width="80px" size="mini">
        <el-form-item :rules="[
          { required: true, message: '请输入终止原因', trigger: 'blur' },
        ]" label="终止原因" prop="contractEndReason">
          <el-input v-model="formTermination.contractEndReason" :rows="4" placeholder="请输入内容" type="textarea">
          </el-input>
        </el-form-item>
        <el-form-item :rules="[
          { required: true, message: '请选择终止时间', trigger: 'change' },
        ]" label="终止时间" prop="contractEndTime">
          <el-date-picker v-model="formTermination.contractEndTime" placeholder="选择日期" type="date"></el-date-picker>
        </el-form-item>
        <el-form-item :rules="[
          { required: true, message: '请上传合同附件', trigger: 'change' },
        ]" label="合同附件" prop="contractFileAttrs">
          <image-upload v-model="formTermination.contractFileAttrs" :isShowTip="false" :limit="2"
                        @input="handleImageInput"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTermination">确 定</el-button>
        <el-button @click="isTerminationOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置打卡地点 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCheckInOpen" append-to-body
               title="设置打卡范围"
               width="80%">
      <AMap v-if="isCheckInOpen" :center="checkInForm.enter" :position="checkInForm.position"
            :radius="checkInForm.range" @getLocation="handleGetLocation"></AMap>
      <el-form ref="checkInForm" :model="checkInForm" :rules="rulesCheckIn" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-col :span="8" class="map-search-input">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="checkInForm.longitude" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="map-search-input">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="checkInForm.latitude" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7" class="map-search-input">
            <el-form-item label="范围(米)" prop="range">
              <el-select v-model="checkInForm.range" @change="handleChangeMapRange">
                <!--                <el-input type="text" v-model="checkInForm.range" @input="(v)=>(checkInForm.range=v.replace(/[^\d]/g,''))"></el-input>-->
                <el-option :value="100"></el-option>
                <el-option :value="200"></el-option>
                <el-option :value="300"></el-option>
                <el-option :value="400"></el-option>
                <el-option :value="500"></el-option>
                <el-option :value="600"></el-option>
                <el-option :value="700"></el-option>
                <el-option :value="800"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheckIn">确 定</el-button>
        <el-button @click="isCheckInOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {clockIn, getProject, listProjectContract, projectRenewal, projectTermination} from "@/api/cld/project";
import {addMaterial, listMaterial} from '@/api/cld/material'
import {getSysUserList} from "@/api/system/user";

import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import addProject from "./addProject.vue";
import addContract from "./addContract.vue";
import addConfiguration from "./addConfiguration.vue";
// 接入高德地图
import AMap from "@/views/components/AMap.vue";
// 引入静态字典
import {cldContractStatusOptions} from '@/assets/staticDict'

export default {
  name: "performance",
  dicts: ['cld_project_type', 'cld_project_business', 'cld_project_region', 'cld_project_post', 'cld_project_groups'],
  components: {
    addProject,
    ErpCommodity,
    addContract,
    addConfiguration,
    AMap
  },
  data() {
    return {
      loading: false,
      projectList: [],
      activeSetName: 'project',
      showSearch: true,
      total: 0,
      openSet: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectStatus: 2,
        projectRegion: null,
        projectName: null,
        headPerson: null
      },
      rulesCheckIn: {
        longitude: [
          {required: true, message: "请输入经度", trigger: "blur"}
        ],
        latitude: [
          {required: true, message: "请输入维度", trigger: "blur"}
        ],
        range: [
          {required: true, message: "请选择打卡范围", trigger: "blur"}
        ],
      },
      // 当前选中项目对象
      projectObj: {},
      personOptions: [],
      //合同状态(1履约2到期3终止)
      cldContractStatusOptions: cldContractStatusOptions,
      // 物资配送阈值
      materialList: [],
      // 商品弹框
      isCommodityOpen: false,
      // 商品过滤
      notCommodityIds: [],
      // 商品临时存放
      temporyList: [],
      // 项目终止弹框
      isTerminationOpen: false,
      // 项目终止表单
      formTermination: {},
      // 设置打卡地点
      isCheckInOpen: false,
      // 打卡设置表单
      checkInForm: {}
    };
  },
  created() {
    this.getContractList();
    this.handleListSysUser();
  },
  methods: {
    // 获取列表
    getContractList() {
      this.loading = true;
      listProjectContract(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取用户列表
    handleListSysUser() {
      getSysUserList().then(res => {
        this.personOptions = res.data;
      })
    },
    // 搜索
    handleContractQuery() {
      this.queryParams.pageNum = 1;
      this.getContractList();
    },
    /** 重置按钮操作 */
    resetContractQuery() {
      this.resetForm("queryForm");
      this.handleContractQuery();
    },
    // 选项卡切换
    handleTabClick() {
      switch (this.activeSetName) {
        case 'material':
          this.handleGetMaterialList();
          break;
      }
    },
    // 计划设置
    handleProfitEstimation(row) {
      this.$router.push("/project/profitEstimation/profitEstimation/" + row.projectId);
    },
    /** 新增项目配置操作 */
    handleContractSet(row) {
      this.activeSetName = 'project';
      // 设置项目id
      this.projectId = row.projectId;
      this.projectObj = row;
      this.openSet = true;
    },
    // 取消
    cancel() {
      this.openSet = false;
    },

    // 物资配送
    handleGetMaterialList() {
      listMaterial(this.projectId).then(res => {
        this.materialList = res.data;
      })
    },
    /** 提交按钮 */
    submitSetForm() {
      if (this.activeSetName == 'project') {
        this.$refs.addProject.submitForm();
      }
      if (this.activeSetName == 'contract') {
        this.$refs.addContract.submitSignForm();
      }
      if (this.activeSetName == 'groupConfig') {
        this.$refs.addConfiguration.submitSetForm();
      }
      if (this.activeSetName == 'material') {
        if (this.materialList.length == 0) {
          this.$modal.error("请选择商品信息");
          return;
        }
        let form = {
          projectId: this.projectId,
          materialList: this.materialList
        }
        addMaterial(form).then(res => {
          this.$modal.msgSuccess("操作成功");
          this.handleSubmiSuccess(this.activeSetName);
        })
      }
    },
    // 设置打卡范围提交
    submitCheckIn() {
      this.$refs["checkInForm"].validate(valid => {
        if (valid) {
          clockIn(this.checkInForm).then(res => {
            this.$modal.msgSuccess("操作成功");
            this.isCheckInOpen = false;
          })
        }
      })
    },
    // 选择商品
    handleAddCommodity() {
      this.notCommodityIds = this.materialList.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach(item => {
        this.materialList.push({
          ...item,
          commodityNum: '500',
          projectId: this.projectId,
        })
      })
      this.isCommodityOpen = false;
    },
    /** 删除商品 */
    handleDeleteCommodity(row) {
      const index = this.materialList.indexOf(row);
      if (index > -1) {
        this.materialList.splice(index, 1);
      }
      this.notCommodityIds = this.notCommodityIds.filter(function (item) {
        return item !== row.commodityId;
      });
    },
    // 终止项目
    handleTermination(row) {
      this.formTermination.projectId = row.projectId;
      this.isTerminationOpen = true;
    },
    // 项目终止表单提交
    submitTermination() {
      this.$refs["formTermination"].validate(valid => {
        if (valid) {
          projectTermination({
            ...this.formTermination,
            contractStatus: 3
          }).then(response => {
            this.getContractList();
            this.$modal.msgSuccess("操作成功");
            this.isTerminationOpen = false;
          });
        }
      });
    },
    // 项目终止 合同附件回调
    handleImageInput(e) {
      this.formTermination.contractFileAttrs = e;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleAddGroup':
          this.$router.push("/project/add-group/groupList/" + row.projectId);
          break;
        case "handleAddWorkPlan":
          this.$router.push("/project/add-workPlan/workPlanList/" + row.projectId);
          break;
        case "handleCheckIn":
          this.checkInForm = {};
          getProject(row.projectId).then(res => {
            this.checkInForm = res.data;
            this.checkInForm.position = [];
            if (this.checkInForm.longitude && this.checkInForm.latitude) {
              this.checkInForm.position = [this.checkInForm.longitude, this.checkInForm.latitude];
            } else {
              this.checkInForm.position = [113.138919, 27.831329];
              this.checkInForm.range = 100;
              this.checkInForm.longitude = this.checkInForm.position[0];
              this.checkInForm.latitude = this.checkInForm.position[1];
            }
            this.isCheckInOpen = true;
          })
          break;
        case "handleAddProjectAssets":
          this.$router.push("/project/add-projectAssets/projectAssetsList/" + row.projectId);
          break;
        case "handleViewPost":
          this.$router.push("/project/view-projectPost/viewProjectPost/" + row.projectId);
          break;
        case "handleAddCustomerAccount":
          this.$router.push("/project/add-customerAccount/accountList/" + row.projectId);
          break;
        case "handleRenewal":
          this.$modal.confirm('是否确认续签项目名称为"' + row.projectName + '"的数据项？').then(function () {
            return projectRenewal(row.projectId);
          }).then(() => {
            this.getContractList();
            this.$modal.msgSuccess("项目续签成功");
          }).catch(() => {
          });
          break;
        default:
          break;
      }
    },
    // 保存成功回调
    handleSubmiSuccess() {
      switch (this.activeSetName) {
        case 'project':
          this.activeSetName = 'contract';
          break;
        case 'contract':
          this.activeSetName = 'groupConfig';
          break;
        case 'groupConfig':
          this.activeSetName = 'material';
          break;
        case 'material':
          this.openSet = false;
          break;
      }
    },
    // 地图点击回调
    handleGetLocation(e) {
      this.checkInForm.longitude = e.lng;
      this.checkInForm.latitude = e.lat;
      this.checkInForm.position = [e.lng, e.lat];
    },
    // 地图输入范围变更回调
    handleChangeMapRange(e) {
      this.checkInForm.range = e;
    }
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.map-search-input {
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
}
</style>
